import React, { useEffect, useState } from 'react';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import {
  Modal,
  Spin,
  message,
  Radio,
  Select,
  Tooltip,
  Button,
  ConfigProvider,
  Table,
  DatePicker,
  Space,
} from 'antd';
import { tableLocale } from '@/tool/components/PageEmpty';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';
import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components/index.js';
import type {
  IPostFindQuoteStationDataParamsType,
  IQuoteStationDataType,
  IDataListType,
  IDataSourceListType,
  IFormValue,
  IReferenceStrategyDataType,
} from '../../../type';
import { IUseType, IResetType } from '../../../type';
import { ReferenceStrategyEcharts } from '../../../components/Charts/index.js';
import { TIME_ENUM } from '../../../tool';
import { postFindQuoteStationData, postQueryRateData } from '../../../service';
import { defaultPointerNum } from '../../../dictionary';
import styles from './index.less';
import 'moment/locale/zh-cn';
import type { Moment } from 'moment';
import moment from 'moment';

interface IProps {
  /**
   * 请求数据
   */
  formValue?: IFormValue;
  /**
   * 菜单code
   */
  menuCode?: string;
  /**
   * 交易单元id
   */
  stationId?: string;
  /**
   * 引用交易单元
   */
  quoteStationId?: string;
  /**
   * 确认引用
   */
  onSubmit?: (data: IReferenceStrategyDataType) => void;
  onPress: (data: Record<string, any>) => void;
}

const ReferenceStrategyModalComponent = (props: IProps) => {
  const pointerNums = TIME_ENUM(defaultPointerNum);
  const { onPress, menuCode, stationId, quoteStationId, formValue, onSubmit } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isError, setIsError] = useState<boolean>(false);
  const [quoteStationData, setQuoteStationData] = useState<IQuoteStationDataType[]>([]);
  const [dataSourceList, setDataSourceList] = useState<IDataSourceListType[]>([]);
  const [nowStationId, setNowStationId] = useState<string>();
  const [adjustPolicyData, setAdjustPolicyData] = useState<IDataListType[]>([]);
  const [adjustPolicyEchartsData, setAdjustPolicyEchartsData] = useState<IDataListType[]>([]);
  const [calendarDate, setCalendarDate] = useState<string | undefined>(formValue!.calendarDate);

  // 调整策略编辑列表数据
  const queryRateData = async (params?: IFormValue) => {
    setIsLoading(true);
    const res = await postQueryRateData(params || {});
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setIsError(false);
      const { dataList = [], defaultCapacity = '0.000' } = res?.data || {};
      const _adjustPolicyData: IDataListType[] = dataList.map(
        (item: IDataListType, index: number) => {
          return {
            ...item,
            beginTime: pointerNums[item?.beginIndex ?? 0] ?? '',
            endTime: pointerNums[item?.endIndex ?? 0] ?? '',
            maxValue: item?.maxValue ?? defaultCapacity,
            minValue: item?.minValue ?? '0.000',
            fixedValue: item?.fixedValue ?? '0.000',
            id: index + 1,
          };
        },
      );
      let _adjustPolicyEchartsData: IDataListType[] = [];
      dataList.forEach((item: IDataListType, index: number) => {
        const isReveal = Number(item.endIndex) > Number(item.beginIndex);
        const beginIndex: number = (isReveal ? item.beginIndex : item.endIndex) ?? 0;
        const endIndex: number = (isReveal ? item.endIndex : item.beginIndex) ?? 95;
        if (beginIndex === endIndex) {
          _adjustPolicyEchartsData.push({
            beginTime: pointerNums[beginIndex],
            rateValue: item?.useType === IUseType.DATASOURCE ? item?.rateValue ?? 100 : '-',
            maxValue:
              item?.useType === IUseType.DATASOURCE ? item?.maxValue ?? defaultCapacity : '-',
            minValue: item?.useType === IUseType.DATASOURCE ? item?.minValue ?? '0.000' : '-',
            fixedValue: item?.useType === IUseType.FIXATION ? item?.fixedValue ?? '0.000' : '-',
            id: index + 1,
          });
        } else {
          for (let a: number = beginIndex; a <= endIndex; a++) {
            _adjustPolicyEchartsData.push({
              beginTime: pointerNums[a],
              rateValue: item?.useType === IUseType.DATASOURCE ? item?.rateValue ?? 100 : '-',
              maxValue:
                item?.useType === IUseType.DATASOURCE ? item?.maxValue ?? defaultCapacity : '-',
              minValue: item?.useType === IUseType.DATASOURCE ? item?.minValue ?? '0.000' : '-',
              fixedValue: item?.useType === IUseType.FIXATION ? item?.fixedValue ?? '0.000' : '-',
              id: index + 1,
            });
          }
        }
      });
      const arr: IDataListType[] = [];
      pointerNums.forEach((i) => {
        const obj = _adjustPolicyEchartsData.find((item) => item.beginTime === i) || {
          beginTime: '-',
          rateValue: '-',
          maxValue: '-',
          minValue: '-',
          fixedValue: '-',
        };
        arr.push(obj);
      });
      _adjustPolicyEchartsData = arr;
      setAdjustPolicyEchartsData(_adjustPolicyEchartsData);
      setDataSourceList(res?.data?.dataSourceList || []);
      setAdjustPolicyData(_adjustPolicyData);
    } else {
      setIsError(true);
      message.error(res?.message || '系统异常');
    }
    setIsLoading(false);
  };

  const fetchData = async (params: IPostFindQuoteStationDataParamsType) => {
    setLoading(true);
    const res = await postFindQuoteStationData(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setError(false);
      const _stationId =
        quoteStationId &&
        (res?.data || []).find((item: any) => item?.stationId === Number(quoteStationId))
          ? Number(quoteStationId)
          : (res?.data || [])[0]?.stationId;

      setNowStationId(_stationId);
      const _params = {
        ...formValue,
        stationId: _stationId,
        reset: IResetType.NO_RESET,
      };
      setQuoteStationData(res?.data || []);
      queryRateData(_params);
    } else {
      setError(true);
      message.error(res?.message || '系统异常');
    }
    setLoading(false);
  };

  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  const onChangeStation = (e: string) => {
    setNowStationId(e);
  };

  const queryData = () => {
    const _params: IFormValue = {
      ...formValue,
      calendarDate,
      stationId: nowStationId,
      reset: IResetType.NO_RESET,
    };
    queryRateData(_params);
  };

  const _onSubmit = async () => {
    const _data: IReferenceStrategyDataType = {
      quoteStationId: nowStationId,
      quoteDataList: adjustPolicyData,
    };
    onSubmit && onSubmit(_data);
    setVisible(false);
    onPress({ index: 1 });
  };

  useEffect(() => {
    if (menuCode) {
      const _params = {
        menuCode,
        stationId,
      };
      fetchData(_params);
    }
  }, [menuCode]);

  const columns = [
    {
      title: '时间段',
      dataIndex: 'beginTime',
      key: 'beginTime',
      align: 'center',
      width: 120,
      render(v: string, record: IDataListType) {
        return (
          <div className={styles.timeSlot}>
            <span className={styles.beginTime}>{record?.beginTime || ''}</span>
            <span> - </span>
            <span className={styles.endTime}>{record?.endTime || ''}</span>
          </div>
        );
      },
    },
    {
      dataIndex: 'dataSourceId',
      key: 'dataSourceId',
      title: (
        <div className={styles.dataSourceId}>
          <div className={styles.radio}>{''}</div>
          <div className={styles.ratio}>调整比例(%)</div>
          <div className={styles.predictSource}>基准预测源</div>
          <div className={styles.maxNum}>最大值</div>
          <div className={styles.minNum}>最小值</div>
        </div>
      ),
      width: 295,
      render(v: string, record: IDataListType) {
        return (
          <div className={styles.dataSourceIdShow}>
            <div className={styles.radio}>
              <Radio checked={record?.useType === IUseType.DATASOURCE} disabled />
            </div>
            <div className={styles.ratio}>{record?.rateValue ?? 100}</div>
            <div className={styles.predictSource}>
              <Tooltip
                placement="topLeft"
                title={
                  dataSourceList?.find((item) => {
                    return item.masterId === record?.masterId;
                  })?.dataSourceName
                }
              >
                {dataSourceList?.find((item) => {
                  return item.masterId === record?.masterId;
                })?.dataSourceName || '-'}
              </Tooltip>
            </div>
            <div className={styles.maxNum}>{record?.maxValue ?? '0.000'}</div>
            <div className={styles.minNum}>{record?.minValue ?? '0.000'}</div>
          </div>
        );
      },
    },
    {
      dataIndex: 'fixedValue',
      key: 'fixedValue',
      title: (
        <div className={styles.fixedValue}>
          <div className={styles.radio}>{''}</div>
          <div className={styles.name}>固定值</div>
        </div>
      ),
      width: 100,
      render(v: string, record: IDataListType) {
        return (
          <div className={styles.fixedValueShow}>
            <div className={styles.radio}>
              <Radio checked={record?.useType === IUseType.FIXATION} disabled />
            </div>
            <div className={styles.fixedValueShowInput}>{record?.fixedValue ?? '0.000'}</div>
          </div>
        );
      },
    },
  ];

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { label } = option;
    return label?.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={loading || isLoading}>
      取消
    </Button>,
    <Button
      key="dtest2"
      type="primary"
      onClick={_onSubmit}
      loading={loading || isLoading}
      style={{ marginLeft: 16 }}
    >
      确定
    </Button>,
  ];

  const dateChange = (_: Moment | null, dataString: string) => {
    setCalendarDate(dataString);
  };

  return (
    <Modal
      className={styles.modal}
      centered
      width={1200}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <div className={styles.left}>
            <img src={planIcon} className={styles.titleLogo} />
            <span className={styles.title}>策略引用</span>
          </div>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin />
        ) : error ? (
          <TRDefault type={'error'} message={'系统异常'} />
        ) : (
          <div className={styles.content}>
            <div className={styles.header}>
              <div className={styles.select}>
                <ConfigProvider locale={zh_CN}>
                  <Space size={'middle'}>
                    <Select
                      value={nowStationId as any}
                      optionLabelProp="label"
                      onChange={onChangeStation}
                      filterOption={filterOption as any}
                      placeholder={'请选择交易单元'}
                      showArrow
                      showSearch
                    >
                      {quoteStationData.map((item) => {
                        return (
                          <Select.Option
                            key={item?.stationId}
                            value={item?.stationId || 0}
                            label={item?.stationName}
                          >
                            <div className={styles.options}>
                              <Tooltip placement="topLeft" title={item?.stationName}>
                                {item?.stationName || ''}
                              </Tooltip>
                            </div>
                          </Select.Option>
                        );
                      })}
                    </Select>
                    <DatePicker
                      value={moment(calendarDate)}
                      format="YYYYMMDD"
                      placeholder="请选择"
                      className={styles.datePicker}
                      onChange={dateChange}
                    />
                    <Button type="primary" onClick={queryData} className={styles.searchBtn}>
                      查询
                    </Button>
                  </Space>
                </ConfigProvider>
              </div>
            </div>
            <div className={styles.bottom}>
              {isLoading ? (
                <Spin />
              ) : isError ? (
                <TRDefault type={'error'} message={'系统异常'} />
              ) : adjustPolicyData.length ? (
                <div className={styles.bottomContent}>
                  <div className={styles.left}>
                    <ReferenceStrategyEcharts
                      data={adjustPolicyEchartsData}
                      date={formValue?.calendarDate}
                    />
                  </div>
                  <div className={styles.right}>
                    <div className={styles.table}>
                      <Table
                        dataSource={adjustPolicyData}
                        columns={columns as any}
                        pagination={false}
                        locale={tableLocale}
                        bordered
                        scroll={{ y: 460 }}
                      />
                    </div>
                  </div>
                </div>
              ) : (
                <TRDefault type={'emptysm'} message={'暂无数据'} />
              )}
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
};

class ReferenceStrategyModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ReferenceStrategyModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ReferenceStrategyModal();
